package examonline.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import examonline.model.Exam_Exam;
import examonline.model.Exam_ExamDetails;
import examonline.model.Exam_Project;
import examonline.model.Exam_Question;
import examonline.model.Exam_Questiontype;
import examonline.model.Exam_Result;
import examonline.model.Exam_Subject;
import examonline.model.Exam_SysUser;
import examonline.model.Exam_User;
import examonline.model.Exam_UserPaper;
import examonline.model.Exam_upq;
import examonline.model.RecordAdmin;
import examonline.uilt.FastJsonUilt;
import examonline.uilt.ServiceReturnUilt;

@SuppressWarnings({ "unused", "rawtypes" })
public class ExamServiceAdmin extends ExamService {
	private RecordAdmin recordAdmin = new RecordAdmin();
	private Exam_SysUser sysUser = new Exam_SysUser();
	public Map geteqUserPaperPage(Map map) {
		Map<String, Object> remap = new HashMap<String, Object>();
		Page page = this.eqUserPaper.page(map);
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", page.getList());
		remap.put("recordsTotal", page.getTotalRow());
		remap.put("recordsFiltered", page.getTotalRow());
		return remap;
	}

	public Map geteqQuestion(Map map) {
		Map<String, Object> remap = new HashMap<String, Object>();
		Page page = this.eqQuestion.pages(map);
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", page.getList());
		remap.put("recordsTotal", page.getTotalRow());
		remap.put("recordsFiltered", page.getTotalRow());
		return remap;
	}

	public Map getExam(Map map) {
		Map<String, Object> remap = new HashMap<String, Object>();
		Page page = super.eqExam.page(map);
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", page.getList());
		remap.put("recordsTotal", page.getTotalRow());
		remap.put("recordsFiltered", page.getTotalRow());
		return remap;
	}

	public Map getMarking(Map map) {
		Map<String, Object> remap = new HashMap<String, Object>();
		Page page = super.eqExam.page(map);
		List<Exam_Exam> list = page.getList();
		List<ExamPapers> relist = new ArrayList<ExamPapers>();
		for (Exam_Exam ee : list) {
			ExamPapers ep = new ExamPapers();
			int examid = ee.get("id");
			ep.setExam(ee);
			ep.setList(eqUserPaper.getByAttrNameValue("examid", String.valueOf(examid)));
			relist.add(ep);
		}
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", relist);
		remap.put("recordsTotal", page.getTotalRow());
		remap.put("recordsFiltered", page.getTotalRow());
		return remap;
	}

	public class ExamPapers {
		private Exam_Exam exam;
		private List<Exam_UserPaper> list;

		public Exam_Exam getExam() {
			return exam;
		}

		public void setExam(Exam_Exam exam) {
			this.exam = exam;
		}

		public List<Exam_UserPaper> getList() {
			return list;
		}

		public void setList(List<Exam_UserPaper> list) {
			this.list = list;
		}

	}

	// 获取试卷对应的题目
	public Map getQuestions(String ExamPaperId) {
		Map<String, Object> remap = new HashMap<String, Object>();
		List<Exam_upq> qpqlist = eqUpq.getByAttrNameValue("userpaperid", ExamPaperId);
		List<PaperQuestionsResult> relist = new ArrayList<PaperQuestionsResult>();
		for (Exam_upq upq : qpqlist) {
			PaperQuestionsResult pqr = new PaperQuestionsResult();
			// 获取题目
			Exam_Question eq = eqQuestion.getByFirstNameValue("id", upq.get("questionid").toString());
			// 获取题目答案选项
			List<Exam_Result> erl = eqResult.getByAttrNameValue("questionid", eq.getStr("id"));
			pqr.setQuestion(eq);
			pqr.setResults(erl);
			relist.add(pqr);
		}
		Paper paper = new Paper();
		paper.setUpqs(qpqlist);
		paper.setPqrs(relist);
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", paper);
		return remap;
	}

	public class PaperQuestionsResult {
		private Exam_Question question;
		private List<Exam_Result> results;

		public Exam_Question getQuestion() {
			return question;
		}

		public void setQuestion(Exam_Question question) {
			this.question = question;
		}

		public List<Exam_Result> getResults() {
			return results;
		}

		public void setResults(List<Exam_Result> results) {
			this.results = results;
		}

	}

	public class Paper {
		private List<PaperQuestionsResult> pqrs;
		private List<Exam_upq> upqs;

		public List<PaperQuestionsResult> getPqrs() {
			return pqrs;
		}

		public void setPqrs(List<PaperQuestionsResult> pqrs) {
			this.pqrs = pqrs;
		}

		public List<Exam_upq> getUpqs() {
			return upqs;
		}

		public void setUpqs(List<Exam_upq> upqs) {
			this.upqs = upqs;
		}

	}

	/**
	 * 获取考试
	 * 
	 * @return
	 */
	public Map getExamPaper() {
		Map<String, Object> remap = new HashMap<String, Object>();
		String sql = "select *,exam_userpaper.id as pid, exam_userpaper.display as pdisplay  from exam_userpaper LEFT JOIN exam_exam ON exam_userpaper.examid=exam_exam.id";
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", Db.find(sql));
		return remap;
	}

	public Map saveQuestion(Map map) {
		Map questiondata = (Map) map.get("questiondata");
		List<Map> resultdatas = (List<Map>) map.get("resultdatas");
		this.eqQuestion._setAttrs(questiondata);
		Map<String, Object> remap = new HashMap<String, Object>();
		boolean result = this.eqQuestion.save();
		for (Map res : resultdatas) {
			res.put("questionid", this.eqQuestion.get("id"));
			this.eqResult.remove("id");
			this.eqResult._setAttrs(res);
			this.eqResult.save();
		}
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", "");
		return remap;
	}

	public Map saveExam(Map map) {
		super.eqExam.clear();
		super.eqExam._setAttrs(map);
		Map<String, Object> remap = new HashMap<String, Object>();
		boolean result = super.eqExam.save();
		remap.put("result", true);
		remap.put("error", "");
		remap.put("data", result);
		return remap;
	}

	@Before(Tx.class)
	public Map saveQuestionByExcelV2(Map map) {
		Map<String, Object> remap = new HashMap<String, Object>();
		boolean succeed = Db.tx(new IAtom() {
			public boolean run() throws SQLException {
				List questions = (List) map.get("questions");
				for (int i = 0; i < questions.size(); i++) {
					// 读取问题
					JSONObject question = (JSONObject) questions.get(i);
					Map qmap = FastJsonUilt.convertJsonStrToMap(question.toString());
					// 获取问题答案
					List results = (List) qmap.get("results");
					// 问题中移除答案
					qmap.remove("results");
					eqQuestion.clear();
					eqQuestion._setAttrs(qmap);
					// 存入问题
					eqQuestion.save();
					// 遍历答案
					if(results!=null&&results.size()>0) {
					for (int j = 0; j < results.size(); j++) {
						JSONObject result = (JSONObject) results.get(j);
						Map mresult = FastJsonUilt.convertJsonStrToMap(result.toString());
						mresult.put("questionid", eqQuestion.get("id"));
						 // 存入答案 
						eqResult.clear();
						eqResult._setAttrs(mresult); 
						eqResult.save();
					}
					}
				}

				return true;
			}
		});
		remap.put("result", succeed);
		remap.put("error", "");
		remap.put("data", "");
		return remap;
	}

	@SuppressWarnings("unchecked")
	@Before(Tx.class)
	public Map saveQuestionByExcel(Map map) {
		Map<String, Object> remap = new HashMap<String, Object>();
		boolean succeed = Db.tx(new IAtom() {
			public boolean run() throws SQLException {
				// 单选
				List dxquestions = (List) map.get("dxquestions");
				for (int i = 0; i < dxquestions.size(); i++) {
					// 读取问题
					JSONObject question = (JSONObject) dxquestions.get(i);
					Map qmap = FastJsonUilt.convertJsonStrToMap(question.toString());
					// 获取问题答案
					List results = (List) qmap.get("results");
					// 问题中移除答案
					qmap.remove("results"); // 存入问题
					eqQuestion.clear();
					eqQuestion._setAttrs(qmap);
					eqQuestion.save();
					// 遍历答案
					for (int j = 0; j < results.size(); j++) {
						JSONObject result = (JSONObject) results.get(j);
						Map mresult = FastJsonUilt.convertJsonStrToMap(result.toString());
						mresult.put("questionid", eqQuestion.get("id")); // 存入答案 eqResult.clear();
						eqResult.clear();
						eqResult._setAttrs(mresult); // eqResult._setAttrs(mresult);
						eqResult.save();
					}

				} // 多选
				List dxxquestions = (List) map.get("dxxquestions");
				for (int i = 0; i < dxxquestions.size(); i++) {
					// 读取问题
					JSONObject question = (JSONObject) dxxquestions.get(i);
					Map qmap = FastJsonUilt.convertJsonStrToMap(question.toString());
					// 获取问题答案
					List results = (List) qmap.get("results");
					// 问题中移除答案
					qmap.remove("results");
					// 存入问题
					eqQuestion.clear();
					eqQuestion._setAttrs(qmap);
					eqQuestion.save();
					// 遍历答案
					for (int j = 0; j < results.size(); j++) {
						JSONObject result = (JSONObject) results.get(j);
						Map mresult = FastJsonUilt.convertJsonStrToMap(result.toString());
						mresult.put("questionid", eqQuestion.get("id"));
						// 存入答案
						eqResult.clear();
						eqResult._setAttrs(mresult);
						eqResult.save();
					}
				}
				// 判断题
				List pdquestions = (List) map.get("pdquestions");
				for (int i = 0; i < pdquestions.size(); i++) {
					// 读取问题
					JSONObject question = (JSONObject) pdquestions.get(i);
					Map qmap = FastJsonUilt.convertJsonStrToMap(question.toString()); // 存入问题
					eqQuestion.clear();
					eqQuestion._setAttrs(qmap);
					eqQuestion.save();
				}
				// 填空题
				List tkquestions = (List) map.get("tkquestions");
				for (int i = 0; i < tkquestions.size(); i++) {
					// 读取问题
					JSONObject question = (JSONObject) tkquestions.get(i);
					Map qmap = FastJsonUilt.convertJsonStrToMap(question.toString()); // 存入问题
					eqQuestion.clear();
					eqQuestion._setAttrs(qmap);
					eqQuestion.save();
				}

				return true;
			}

		});
		remap.put("result", succeed);
		remap.put("error", "");
		remap.put("data", "");
		return remap;
	}

	public Map getExamDetailsSubPro(Map map) {
		Object examid = map.get("examid");
		Exam_Exam ee = super.eqExam.findById(examid);
		Exam_ExamDetails eed = eqDetails.findById(ee.get("examdetailsid"));
		ExamDetailsSubPro eds = new ExamDetailsSubPro();
		eds.setDetails(eed);
		eds.setExam(ee);
		return ServiceReturnUilt.ServiceReturn(true, eds);
	}

	public class ExamDetailsSubPro {
		private Exam_Exam exam;
		private Exam_ExamDetails details;
		private Exam_Subject subject;
		private Exam_Project project;

		public Exam_Exam getExam() {
			return exam;
		}

		public void setExam(Exam_Exam exam) {
			this.exam = exam;
		}

		public Exam_ExamDetails getDetails() {
			return details;
		}

		public void setDetails(Exam_ExamDetails details) {
			this.details = details;
		}

		public Exam_Subject getSubject() {
			return subject;
		}

		public void setSubject(Exam_Subject subject) {
			this.subject = subject;
		}

		public Exam_Project getProject() {
			return project;
		}

		public void setProject(Exam_Project project) {
			this.project = project;
		}

	}

	public Map getSubPro() {
		List<SubPros> lsup = new ArrayList<SubPros>();
		List<Exam_Subject> les = eqSubject.getAll();
		for (Exam_Subject es : les) {
			List<Exam_Project> lep = eqProject.getByAttrNameValue("subjectid", es.get("id"));
			SubPros sp = new SubPros();
			sp.setProject(lep);
			sp.setSubject(es);
			lsup.add(sp);
		}
		return ServiceReturnUilt.ServiceReturn(true, lsup);
	}

	public Map antionExam(Map map) {
		int action = (int) map.get("action");
		// 修改
		if (action == 0) {
			Map details = (Map) map.get("details");
			Map examm = (Map) map.get("exam");
			super.eqDetails.clear();
			super.eqDetails._setAttrs(details);
			super.eqExam.clear();
			super.eqExam._setAttrs(examm);
			super.eqDetails.update();
			super.eqExam.update();
		} else if (action == 1) {
			Map details = (Map) map.get("details");
			Map examm = (Map) map.get("exam");
			super.eqDetails.clear();
			super.eqDetails._setAttrs(details);
			super.eqDetails.save();
			Exam_ExamDetails eed = this.eqDetails;
			super.eqExam.clear();
			examm.put("examdetailsid", eed.get("id"));
			super.eqExam._setAttrs(examm);
			super.eqExam.save();

		}
		return ServiceReturnUilt.ServiceReturn(true);
	}

	public class SubPros {
		private Exam_Subject subject;
		private List<Exam_Project> project;

		public Exam_Subject getSubject() {
			return subject;
		}

		public void setSubject(Exam_Subject subject) {
			this.subject = subject;
		}

		public List<Exam_Project> getProject() {
			return project;
		}

		public void setProject(List<Exam_Project> project) {
			this.project = project;
		}
	}

	public Map getResultByQuestionId(Map map) {
		List<Exam_Result> model = eqResult.getByAttrNameValue("questionid", map.get("questionid"));
		return ServiceReturnUilt.ServiceReturn(true, model);
	}

	public Map editResult(Map map) {
		List list = (List) map.get("list");
		for (int i = 0; i < list.size(); i++) {
			Map result = (Map) list.get(i);
			eqResult.clear();
			eqResult._setAttrs(result);
			eqResult.update();
		}
		return ServiceReturnUilt.ServiceReturn(true);
	}

	public Map updateQuestion(Map map) {
		Map question = (Map) map.get("question");
		eqQuestion.clear();
		eqQuestion._setAttrs(question);
		return ServiceReturnUilt.ServiceReturn(eqQuestion.update());
	}

	public Map editSubPro(Map map) {
		boolean rebl = false;
		Map subpro = (Map) map.get("subpro");
		int action = (int) subpro.get("action");
		if (action == 1) {
			eqSubject.clear();
			eqSubject.set("id", subpro.get("subjectid"));
			eqSubject.set("name", subpro.get("subtext"));
			eqSubject.update();
			eqProject.clear();
			eqProject.set("id", subpro.get("projectid"));
			eqProject.set("name", subpro.get("protext"));
			eqProject.update();
			rebl = true;
		} else if (action == 2) {
			String sqlPara = "select * from exam_subject es  INNER JOIN exam_project ep ON es.id=ep.subjectid "
					+ " WHERE  es.name='" + subpro.get("subtext") + "' and ep.name='" + subpro.get("protext") + "'";
			// String sqlSub="select * from exam_subject subject where subject.name='"++"'";
			Exam_Subject es = eqSubject.getByFirstNameValue("name", subpro.get("subtext"));
			Exam_Project ep = eqProject.getByFirstNameValue("name", subpro.get("protext"));
			if (es != null && ep == null) {
				eqProject.clear();
				eqProject.set("name", subpro.get("protext"));
				eqProject.set("subjectid", subpro.get("subjectid"));
				eqProject.save();
				rebl = true;
			} else if (es == null && ep == null) {
				eqSubject.clear();
				eqSubject.set("name", subpro.get("subtext"));
				eqSubject.save();
				eqProject.clear();
				eqProject.set("name", subpro.get("protext"));
				eqProject.set("subjectid", eqSubject.get("id"));
				eqProject.save();
				rebl = true;
			}

		}
		return rebl ? ServiceReturnUilt.ServiceReturn(rebl) : ServiceReturnUilt.ServiceReturnError("科目/方案有重复!");
	}

	public Map getUserPaper(Map map) {
		Page page = recordAdmin.userPaperPage(map);
		return ServiceReturnUilt.ServiceReturnRecordPage(page);
	}

	public Map getUqpByMarking(Map map) {
		return ServiceReturnUilt.ServiceReturn(true, recordAdmin.getUqpByMarking(map));
	}

	public Map saveMarking(Map map) {
		Map upqmap = (Map) map.get("upq");
		Map userpapermap = (Map) map.get("userpaper");
		Exam_upq upq = eqUpq.findById(upqmap.get("id"));
		Exam_UserPaper userpaper = eqUserPaper.findById(userpapermap.get("id"));
		upq.set("goal", upqmap.get("goal"));
		userpaper.set("fraction", userpapermap.get("fraction"));
		userpaper.set("teacherid", userpapermap.get("teacherid"));
		upq.update();
		userpaper.update();
		return ServiceReturnUilt.ServiceReturn(true);
	}

	public Map getUsers(Map map) {
		return ServiceReturnUilt.ServiceReturnRecordPage(eqUser.page(map));
	}

	public Map upUser(Map map) {
		Map user = (Map) map.get("user");
		eqUser.clear();
		eqUser._setAttrs(user);
		return ServiceReturnUilt.ServiceReturn(eqUser.update());
	}

	public Map saveUser(Map map) {
		Map user = (Map) map.get("user");
		Exam_User model = eqUser.getByFirstNameValue("workno", user.get("workno"));
		if (model != null) {
			return ServiceReturnUilt.ServiceReturnError("工号:" + user.get("workno") + "已经存在!");
		} else {
			eqUser.clear();
			eqUser._setAttrs(user);
			return ServiceReturnUilt.ServiceReturn(eqUser.save());
		}
	}

	public Map sysDoLogin(Map map) {
		String sql = "select * from exam_sysuser where username='" + map.get("username") + "'" + " and password='"
				+ map.get("password") + "'";
		Exam_SysUser es = sysUser.findFirst(sql);
		if (es == null) {
			return ServiceReturnUilt.ServiceReturnError("用户或密码错误!");
		}
		return ServiceReturnUilt.ServiceReturn(true, es);
	}

	public Map dataExport(Map map) {
		List<String> props = (List) map.get("props");
		Object examid = map.get("examid");
		String sql = "SELECT  exam.name as examname, exam.title as examtitle,user.name as username, "
				+ " user.workno as userworkno,max(userpaper.fraction) as maxfraction,"
				+ " count(1) as userckcs FROM exam_userpaper as userpaper LEFT JOIN exam_exam as exam ON"
				+ " exam.id=userpaper.examid LEFT JOIN exam_user as user ON "
				+ " user.workno=userpaper.workno WHERE  user.workno=userpaper.workno and exam.id='" + examid + "'"
				+ " group by  exam.name,exam.title,user.name,user.workno ";
		/*
		 * for(String prop:props) { if(prop.equals("examname")){
		 * sql=sql+" exam.name as examname,"; }else if(prop.equals("examtitle")){
		 * sql=sql+" exam.title as examtitle,"; }else if(prop.equals("examtime")){
		 * sql=sql+" exam.time as examtime,"; }else if(prop.equals("examstime")){
		 * sql=sql+" exam.stime as examstime,"; }else if(prop.equals("exametime")){
		 * sql=sql+" exam.etime as exametime,"; }else
		 * if(prop.equals("examhascompletion")){
		 * sql=sql+" exam.hascompletion as examhascompletion,"; }else
		 * if(prop.equals("username")){ sql=sql+" user.name as username,"; }else
		 * if(prop.equals("userworkno")){ sql=sql+" user.workno as userworkno,"; }
		 * 
		 * }
		 */
		return ServiceReturnUilt.ServiceReturn(true, Db.find(sql));
	}

}
